package com.example.spring.jpa.ast;

import com.example.spring.jpa.ast.handle.GlobalOperationHandle;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @author: orange
 * @create: 2023-07-22 17:06
 * @description: 分析表达式的入口。
 */
public class AstExpression implements AstNode {
    private final List<GlobalOperationHandle> globalOperationHandles = new ArrayList<>();
    private String content;

    private AstExpression() {}

    public AstExpression(String content) {
        this.content = content;
        ServiceLoader<GlobalOperationHandle> load = ServiceLoader.load(GlobalOperationHandle.class);
        for (GlobalOperationHandle globalOperationHandle : load) {
            globalOperationHandles.add(globalOperationHandle);
        }
        globalOperationHandles.sort((o1, o2) -> {
            return o1.order() - o2.order();
        });
    }

    @Override
    public AstNode parse() throws Exception {
        for (GlobalOperationHandle global : globalOperationHandles) {
            AstNode astNode = global.getAstNode(sentence());
            if (global.isMatch()) {
                return astNode.parse();
            }
        }
        return new AstStatic(this.content);
    }

    @Override
    public String sentence() {
        return this.content;
    }
}
